/**
 * Created by freethy on 2017/10/13.
 */

//上传图片
$(function () {
    $(".match-img").on("click", function () {

        //创建页面元素
        var fileObj = document.createElement("input");
        fileObj.setAttribute("type", "file");
        fileObj.setAttribute("accept", ".jpg,.jpeg,.gif,.png,.bmp");
        fileObj.setAttribute("style", "display:none");
        $(fileObj).change(function () {
            var index = layer.load(0, {shade: 0.2});
            var file = fileObj.files[0];
            var name = window.guid();
            $.upload2oss({
                accessid: accessid,
                accesskey: accesskey,
                host: host,
                file: file,
                key: key + "/" + name + ".png",
                success: function (e, option) {
                    var url = option.host + "/" + option.key;
                    $(".match-img img").attr("src", url);
                    $(".match-img i").hide();
                    $(".match-img img").show();
                    $("[name=matchimg]").val(url);
                },
                progress: function (e) {

                },
                complete: function () {
                    layer.close(index);
                }
            });
        });
        fileObj.click();
    });
});

//页面加载完成
$(function () {
    //搜索的键盘事件
    $(document).keyup(function(event){
        if(event.keyCode ==13){
            $("[enter-search]").trigger("click");
            $(".high_search").hide();
        }
    });
    //移动端页面刷新
    $("[data-reload-app]").on('click',function () {
        window.location.reload();
    });
    //图片预览
    $("body").on("click","[data-picview]",function(){
        var ps = null;
        try
        {
            var s = $(this).data("picview");
            ps = eval("("+s + ")");
        }
        catch(ex)
        {}
        if(ps == null){
            return;
        }

        var obj =  {
            "title": "",
            "id": 123,
            "start": 0,
            "data": []
        };

        for(var i=0;i<ps.length;i++){
            obj.data.push({
                "alt": "",
                "pid": 666, //图片id
                "src": ps[i], //原图地址
                "thumb": ps[i] //缩略图地址
            });
        }

        layer.photos({ photos: obj ,anim: 5,shade: [0.8, '#393D49'] });
    });

    //tab控制
    $(".pt-tab li").on("click", function () {
        $(this).parent().find('li').removeClass("active");
        $(this).addClass("active");
        var v = $(this).data("value");
        $(this).parent().next().find(">div[data-value]").hide();
        $(this).parent().next().find(">div[data-value=" + v + "]").show();
        $(this).parent().trigger('change');
    });
    $(".pt-tab li:eq(0)").trigger("click");

    //数据导出
    $("[pt-export]").on("click", function () {
        var table = $(this).attr("pt-export");
        frame.daochu(table);
    });

    //选择select
    $("select[data-value]").each(function (i, e) {
        var value = $(e).data("value");
        if(value == '') return;
        $(e).val(value);
    });

    //选择radio
    $("input[type=radio][data-value]").each(function (i, e) {
        var value = $(e).data("value");
        if (value == $(e).val()) {
            $(e).attr("checked", "checked");
        }
    });

    //绑定按钮
    $('[data-button]').each(function (i, e) {

        //获取menu_id
        var menu_id = $(e).data('button');
        if (!menu_id) {
            var iframe = func.getCurrentIFrame();
            menu_id = iframe.id.split('-')[1];
        }

        $.ajax({
            url: "/admin/bus/get_button",
            type: "get",
            data: {menu_id: menu_id}
        })
            .done(function (data) {
                //console.log(data);
                var html = '';
                var category = '';
                for (var i = 0; i < data.length; i++) {
                    if (data[i]['category'] != category) {
                        html += '<div class="btn-group btn-group-toggle">';
                    }
                    //html += '<label class="' + data[i]['color'] + ' active"  onclick="' + data[i]['action'] + '" ><input type="radio" autocomplete="off" checked><i class="' + data[i]['ico'] + ' fa-lg"></i> ' + data[i]['name'] + ' </label>';
                    // html += '<label class="' + data[i]['color'] + '"  onclick="' + data[i]['action'] + '" ><input type="radio" autocomplete="off" checked><i class="' + data[i]['ico'] + ' fa-lg"></i> ' + data[i]['name'] + ' </label>';
                    html += '<label class="' + data[i]['color'] + '"  onclick="' + data[i]['action'] + '" > <i class="' + data[i]['ico'] + ' fa-lg"></i> ' + data[i]['name'] + ' </label>';
                    category = data[i]['category'];
                    if (i + 1 >= data.length || data[i + 1]['category'] != category) {
                        html += '</div> ';
                    }
                }

                $(e).html(html);
            });

    });


    //绑定关闭弹窗
    $("[data-close]").on('click', function () {
        var text = $(this).data('close');
        var tindex = parent.layer.confirm(text, {
            btn: ['确定', '取消']
        }, function () {
            parent.layer.close(tindex);
            var index = parent.layer.getFrameIndex(window.name);
            parent.layer.close(index);
        });
    });


});


/*
弹出提示信息
*/
function ptshow(data) {
    if (typeof data == 'string') {
        top.layer.alert(data, {icon: 6, time: 3000});
    } else if (typeof data == 'object') {
        if (data.code == 0) {
            top.layer.alert('操作成功', {icon: 1, time: 2000});
        } else {
            if (data.filter) {
                layer.tips(data.text, data.filter);
                $(data.filter).focus();
            } else {
                top.layer.alert(data.text, {icon: 2, time: 3000});
            }
        }
    }
}

/*
时间戳转时间
*/
function timeStamp2String(value) {

    if (!value || value == '0') {
        return '';
    }
    var datetime = new Date();
    datetime.setTime(value * 1000);
    var year = datetime.getFullYear();
    var month = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
    var date = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
    var hour = datetime.getHours() < 10 ? "0" + datetime.getHours() : datetime.getHours();
    var minute = datetime.getMinutes() < 10 ? "0" + datetime.getMinutes() : datetime.getMinutes();
    var second = datetime.getSeconds() < 10 ? "0" + datetime.getSeconds() : datetime.getSeconds();
    return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
}

/**
 * 当前时间转Y-m-d H:i:s格式
 * @returns {string}
 */
function getFormatDate() {
    var nowDate = new Date();
    var year = nowDate.getFullYear();
    var month = nowDate.getMonth() + 1 < 10 ? "0" + (nowDate.getMonth() + 1) : nowDate.getMonth() + 1;
    var date = nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate.getDate();
    var hour = nowDate.getHours() < 10 ? "0" + nowDate.getHours() : nowDate.getHours();
    var minute = nowDate.getMinutes() < 10 ? "0" + nowDate.getMinutes() : nowDate.getMinutes();
    var second = nowDate.getSeconds() < 10 ? "0" + nowDate.getSeconds() : nowDate.getSeconds();
    return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
}

/*
* 关闭标签卡
* */
function closeTab(tid) {
    //console.log(tid);return;
    var ti = $("a.J_menuTab[data-id='" + tid + "'] i", window.top.document);

    //ti.click();
    ti.trigger('click');
}


$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    var $radio = $('input[type=radio],input[type=checkbox]', this);
    $.each($radio, function () {
        if (!o.hasOwnProperty(this.name)) {
            o[this.name] = '';
        }
    });
    return o;
};


;(function (window) {

    //时间戳转时间 格式 年-月-日 时:分:秒
    function timeStamp2String(value) {

        if (!value || value == '0') {
            return '';
        }
        var datetime = new Date();
        datetime.setTime(value * 1000);
        var year = datetime.getFullYear();
        var month = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
        var date = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
        var hour = datetime.getHours() < 10 ? "0" + datetime.getHours() : datetime.getHours();
        var minute = datetime.getMinutes() < 10 ? "0" + datetime.getMinutes() : datetime.getMinutes();
        var second = datetime.getSeconds() < 10 ? "0" + datetime.getSeconds() : datetime.getSeconds();
        return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
    }

    //时间戳转时间 格式 年-月-日
    function timeStamp3String(value) {

        if (!value || value == '0') {
            return '';
        }
        var datetime = new Date();
        datetime.setTime(value * 1000);
        var year = datetime.getFullYear();
        var month = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
        var date = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
        return year + "-" + month + "-" + date;
    }

    //时间戳转时间 格式 年-月-日 时:分
    function timeStamp4String(value) {

        if (!value || value == '0') {
            return '';
        }
        var datetime = new Date();
        datetime.setTime(value * 1000);
        var year = datetime.getFullYear();
        var month = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
        var date = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
        var hour = datetime.getHours() < 10 ? "0" + datetime.getHours() : datetime.getHours();
        var minute = datetime.getMinutes() < 10 ? "0" + datetime.getMinutes() : datetime.getMinutes();
        var second = datetime.getSeconds() < 10 ? "0" + datetime.getSeconds() : datetime.getSeconds();
        return year + "-" + month + "-" + date + " " + hour + ":" + minute;
    }

    //cst时间转标准格式时间 格式 yyyy-MM-dd HH:mm:ss,不正确的转换，但客户需要
    function timeCST(value) {
        value = value.replace("T", " ");
        value = value.substr(0, value.indexOf("."));
        return value;
    }

    // 验证手机号
    function isPhoneNo(phone) {
        let pattern = /^1\d{10}$/;
        let data = phone.replace(/\s+/g, "");
        return pattern.test(data);
    }

    //iqc检验单状态
    var iqc_inspect_state = function (value) {
        if (value) {
            var html = '';
            if (value == "待检验") {
                html = '<span class="text-info">待检验</span>';
            } else if (value == "检验中") {
                html = '<span class="text-success">检验中</span>';
            } else if (value == "免检验") {
                html = '<span class="text-secondary">免检验</span>';
            } else if (value == "待审核") {
                html = '<span class="text-warning" >待审核</span>';
            } else if (value == "审核退回") {
                html = '<span class="text-danger">审核退回</span>';
            } else if (value == "已结束") {
                html = '<span class="text-muted">已结束</span>';
            } else {
                html = '<span class="text-dark">' + value + '</span>';
            }
            return html;
        }
    }
    //文本提示
    function tips(len){
        return function (value,row,index) {
            if(!value){
                return null;
            }
            var text = value;
            if(value.length >len){
                text = value.substring(0,len)+"...";
                return '<span layer-tips="'+ value +'">'+ text +'</span>';
            } else {
                return text;
            }
        }
    }

    //本框架通用导出方法
    var daochu = function (table) {
        var dg = $(table);
        if (dg.length <= 0) {
            console.log("没找到需要导出的表格");
            return;
        }

        if ((typeof dg.bootstrapTable) == "undefined") {
            console.log("找到的表格不是bootstrapTable对象");
            return;
        }

        var op = dg.bootstrapTable("getOptions");
        var url = op.url;
        var col = op.columns;
        var data = op.queryParams({});

        //获取页面标题
        var title = dg.attr("title");
        if (typeof title == "undefined" || title == "") {
            title = "导出数据";
        }

        // console.log(op);
        // console.log(url);
        // console.log(col);
        // console.log(data);
        // console.log(title);

        //精简columns
        var new_col = [];
        for (var i = 0; i < col.length; i++) {
            // console.log(i);
            var cc = [];
            for (var j = 0; j < col[i].length; j++) {
                if (typeof col[i][j] == "undefined") {
                    continue;
                }
                if (col[i][j]['field'] == "") {
                    continue;
                }
                if (!col[i][j].visible) {
                    continue;
                }
                // if(typeof col[i][j].field == "number"){
                //     continue;
                // }

                var c = {};
                c.title = col[i][j]["title"];
                c.field = col[i][j]["field"];
                c.rowspan = col[i][j]["rowspan"];
                c.colspan = col[i][j]["colspan"];

                if (typeof col[i][j]["formatter"] != "undefined") {
                    var funcName = col[i][j]["formatter"].getName();

                    if (funcName == "timeStamp3String") {
                        c.type = "date";
                    } else if (funcName == "timeStamp2String") {
                        c.type = "time";
                    } else if (funcName == "fen2yuan") {
                        c.type = "money";
                    } else {
                        c.type = "string";
                    }
                } else {
                    c.type = "string";
                }

                cc.push(c);
            }
            new_col.push(cc);
        }

        var cols = JSON.stringify(new_col);
        //console.log(cols);
        //return;

        ///(\w+)/(\w+)/(\w+).*
        var reg = /(\w+)\/(\w+)\/(\w+).*/ig;
        var r = reg.exec(url);
        var m = r[1];
        var c = r[2];
        var f = r[3];

        data.offset = 0;
        data.limit = 999999999;
        data.eee_m = m;
        data.eee_c = c;
        data.eee_f = f;
        data.eee_l = cols;
        data.eee_t = title;

        //定义一个form表单
        var form = $("<form>");
        form.attr("style", "display:none");
        form.attr("target", "_blank");
        form.attr("method", "post");
        form.attr("action", "/admin/export/d");

        //遍历
        for (var key in data) {
            var input = $("<input>");
            input.attr("type", "hidden");
            input.attr("name", key);
            input.attr("value", data[key]);
            form.append(input);
        }

        //将表单放置在web中
        $("body").append(form);

        //表单提交
        form.submit();
    }

    //表格格式化上传
    var upload = function (value, row, index) {
        return "<a data-upload='" + value + "' data-index='" + index + "'>管理附件</a>";
    }

    //表格格式化上传
    var uploads = function (value, row, index) {
        return "<a data-uploads='" + value + "' data-index='" + index + "'>管理附件</a>";
    }
    //上传文件界面
    var uploadView = function (rel) {
        layer.open({
            title: '上传文件'
            , type: 2
            , fix: true
            , area: ['700px', '500px']
            , maxmin: false
            , content: '/bus/upload/info?rel=' + rel,
            yes: function (ee) {
                console.log(ee);
            }
        });
    }



    //提交数据到服务器
    var ajax = function (option) {
        option.data.tokenUser = localStorage.getItem('tokenUser').trim();
        //弹出load
        var index = layer.load(2, {icon: 2, shade: 0.1});
        return new Promise(function (resolve, reject) {
            $.ajax(option)
                .done(function (data, textStatus, jqXHR) {
                    if(data.code == 403){
                        layer.alert(data.msg,function()
                        {
                            parent.window.location.href='/bus/index/index';
                        })
                    }else
                    {
                        resolve(data);
                    }
                })
                .fail(function (jqXHR, textStatus, errorThrown) {

                    var text = '';
                    if (jqXHR.status == 0) {
                        text = "服务器连接失败！";
                    } else if (jqXHR.status == 403) {
                        text = "没有权限,请联系管理员！";
                    } else if (jqXHR.status == 500) {
                        var html = jqXHR.responseText;
                        var reg = /<h1>([^<]*)</;
                        var res = reg.exec(html);
                        if (res) {
                            text = res[1];
                        } else {
                            text = "服务器内部错误,请联系管理员！";
                        }
                    } else {
                        text = "未知错误,请联系管理员！";
                    }

                    layer.msg("操作失败：" + text, {icon: 5});

                    reject(jqXHR);
                })
                .always(function () {
                    layer.close(index);
                });
        });
    }

    //提交数据到服务器
    var ajax1 = function (option) {

        return new Promise(function (resolve, reject) {
            $.ajax(option)
                .done(function (data, textStatus, jqXHR) {
                    resolve(data);
                })
                .fail(function (jqXHR, textStatus, errorThrown) {

                    var text = '';
                    if (jqXHR.status == 0) {
                        text = "服务器连接失败！";
                    } else if (jqXHR.status == 403) {
                        text = "没有权限,请联系管理员！";
                    } else if (jqXHR.status == 500) {
                        var html = jqXHR.responseText;
                        var reg = /<h1>([^<]*)</;
                        var res = reg.exec(html);
                        if (res) {
                            text = res[1];
                        } else {
                            text = "服务器内部错误,请联系管理员！";
                        }
                    } else {
                        text = "未知错误,请联系管理员！";
                    }

                    reject({code: 1, text: "操作失败：" + text});
                })
        });
    }


    //弹出提示信息
    function show(data, callback) {
        if (typeof data == 'string') {
            layer.alert(data, {icon: 6, time: 3000});
        } else if (typeof data == 'object') {
            if (data.code == 0) {
                layer.alert('操作成功', {icon: 1, time: 2000});
            } else {
                if (data.filter) {
                    layer.tips(data.text, data.filter);
                    $(data.filter).focus();
                } else {
                    layer.alert(data.text, {icon: 2, time: 3000});
                }
            }
        }
    }

    //绑定用户选择
    function bindUser(userId, userName) {
        var un = $("[name=" + userName + "]");
        var ui = $("[name=" + userId + "]");

        un.fSuggest({
            url: "/admin/bus/user_lst?key=",
            idField: "id",
            textField: "name",
            columns: [
                {"field": "id", title: "id"},
                {"field": "name", title: "姓名"},
                {"field": "number", title: "工号"}
            ]
        });

        un.on("onSelect", function (event, id, txt, rowData, fdata) {
            ui.val(id);
        });

        un.on("onUnSelect", function (event, id, txt, rowData, fdata) {
            ui.val("");
        });
    }

    //关闭当前弹层
    function closeFrame() {
        var index = parent.layer.getFrameIndex(window.name);
        parent.layer.close(index);
    }

    //输出变量
    window.frame = {
        uploadView: uploadView,
        daochu: daochu,
        upload: upload,
        uploads: uploads,
        ajax: ajax,
        ajax1000000: ajax1,
        show: show,
        tips:tips,
        iqc_inspect_state: iqc_inspect_state,
        timeStamp2String: timeStamp2String,
        timeStamp3String: timeStamp3String,
        timeCST: timeCST,
        bindUser: bindUser,
        getFormatDate: getFormatDate,
        closeFrame: closeFrame,
        timeStamp4String: timeStamp4String,
        isPhoneNo: isPhoneNo
    }

})(window);